package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"zg3/config"
	"zg3/internal/models/dao"
	"zg3/internal/models/service"
)

type Node struct {
	conn *websocket.Conn
	data chan []byte
}

var ClientChat = make(map[int]*Node)

func Chat(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("userId"))
	friendId, _ := strconv.Atoi(c.Query("friendId"))
	upgrade := websocket.Upgrader{
		//允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, _ := upgrade.Upgrade(c.Writer, c.Request, nil)
	node := &Node{
		conn: conn,
		data: make(chan []byte, 1024),
	}

	friend := service.FindFriend(friendId, userId)
	if friend != "" {
		log.Println(friend)
		node.conn.Close()
		return
	}

	ClientChat[userId] = node

	go SendMessage(node)

	go ReadMessage(node)

}

func SendMessage(node *Node) {
	for {
		select {
		case data := <-node.data:
			err := node.conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				node.conn.Close()
				return
			}
		}
	}
}

func ReadMessage(node *Node) {
	for {
		_, p, err := node.conn.ReadMessage()
		if err != nil {
			node.conn.Close()
			return
		}
		var message *dao.FriendMessage
		json.Unmarshal(p, &message)
		config.DB.Create(&message)
		n := ClientChat[message.FriendId]
		n.data <- p
	}
}
